﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using tcm.entity.Device;
using tcm.Filters;
using tcm.request.Device;
using tcm.response;
using tcm.utils;

namespace tcm.Controller.DeviceManage
{
    [ApiController]
    [Route("tcm/devicelog")]
    public class DeviceLogController : GCCAPIControllerBase
    {
        private readonly AbsGCCContext _context;
        public DeviceLogController(AbsGCCContext context) : base(context)
        {
            _context = context;
        }

        #region 设备维修管理
        /// <summary>
        /// 查询设备维修列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlist")]
        [TCMAuth(permission: "equipment:maintenance:list")]
        public DataResponse<List<DeviceLogSelect>> GetList([FromQuery] DeviceLogRequest request)
        {
            var sql = new StringBuilder();

            _=sql.Append("select dl.*, s.site_name,s.id as site_id,d.device_name " +
                        "from tcm_device_log dl " +
                        "left join tcm_device d on d.id=dl.device_id " +
                        "left join tcm_site s on s.id=d.site_id " +
                        "where 1=1 ");

            if (!string.IsNullOrWhiteSpace(request.device_name))
                _=sql.Append(string.Format(" and  d.device_name like '%{0}%'", request.device_name));
            //if(request.start_date!=null)
            //    _=sql.Append(string.Format(" and dl.create_date >= '{0}' ", request.start_date));
            //if (request.end_date!=null)
            //    _=sql.Append(string.Format(" and dl.create_date <=  '{0}' ", request.end_date));

            //_=sql.Append(" order by dl.create_date desc  ");
            var dbres = GCCEntrance.DBManager!.LocalDB!.Select<DeviceLogSelect>()
                .WithSql(sql.ToString())
                .WhereIf(request.start_date != null, x => x.create_date >= request.start_date)
                .WhereIf(request.end_date != null, x => x.create_date <= request.end_date)
                .Count(out var count)
                .Page(request.PageIndex ?? 1, request.PageSize)
                .OrderByDescending(x=>x.create_date)
                .ToList();
  
            return HandleData(dbres, count);
        }

        /// <summary>
        /// 查询设备维修表详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("get/{id}")]
        public DataResponse<DeviceLogSelect> GetDeviceLog([FromRoute] long id)
        {
            if(id<=0)
                return SystemError<DeviceLogSelect>("请输入id");
            var sql = new StringBuilder();
             

            _=sql.Append("select dl.*, s.site_name,s.id as site_id,d.device_name " +
                        "from tcm_device_log dl " +
                        "left join tcm_device d on d.id=dl.device_id " +
                        "left join tcm_site s on s.id=d.site_id " +
                        "where dl.id="+id);


            var res = GCCEntrance.DBManager!.LocalDB!.Select<DeviceLogSelect>().WithSql(sql.ToString()).First();

            return HandleData(res);
        }


        /// <summary>
        /// 添加设备维修
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        [TCMAuth(permission: "equipment:maintenance:add")]
        public DataResponse<bool> AddDevice([FromBody] DeviceLogDto request)
        {
            var saveRes = false;
            GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
            {
                request.Create(_context, HttpContext.GetToken()).Wait();
                DeviceLog deviceLog = BeanUtils.copy<DeviceLog, DeviceLogDto>(request);
              
                if (GCCEntrance.DBManager!.LocalDB!.Insert(deviceLog).ExecuteAffrows() != 1)
                {
                    throw new Exception();
                }
                saveRes=true;
            });

            return HandleData(saveRes);
        }

        /// <summary>
        /// 更新设备维修
        /// </summary>
        /// <returns></returns>
        [HttpPost("update")]
        [TCMAuth(permission: "equipment:maintenance:update")]
        public DataResponse<bool> UpdateDevice([FromBody] DeviceLogDto request)
        {
            var saveRes = false;
            if (request.id<=0)
                return SystemError<bool>("id为空");

            var deviceLog = GCCEntrance.DBManager.LocalDB.Select<DeviceLog>().Where(a => a.id == request.id).First();
            if (deviceLog==null)
                return SystemError<bool>("设备不存在");

            request.create_by = deviceLog.create_by;
            request.create_date = deviceLog.create_date;
            request.Modify(_context, HttpContext.GetToken()).Wait();
            BeanUtils.copy<DeviceLog, DeviceLogDto>(request, ref deviceLog);

            if (GCCEntrance.DBManager.LocalDB.Update<DeviceLog>(request.id).SetSource(deviceLog).ExecuteAffrows()>0)
            {
                return HandleData(true);
            }

            return HandleData(saveRes);
        }

        #endregion
    }
}
